import APIZPZ from "../../../utils/apiZpz";
const dayByChiness = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNum: 0,
    padNum: 0,
    datePopupVisible: false,//时间选择弹出层
    userInfo: <any>{},
    date: <any>[],
    pickUpTime: '',
    agreement: false,
    expressTipVisible: false,
    priceTipVisible: false,
    dayIndex: 0,
    timeIndex: 0,
    selectedIndex: '',
    oldTime: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setStorageSync('addressId', undefined);
  },
  phoneMinus() {
    this.setData({
      phoneNum: this.data.phoneNum === 0 ? 0 : --this.data.phoneNum
    })
  },
  phonePlus() {
    this.setData({
      phoneNum: this.data.phoneNum >= 99 ? 99 : ++this.data.phoneNum
    })
  },
  padMinus() {
    this.setData({
      padNum: this.data.padNum === 0 ? 0 : --this.data.padNum
    })
  },
  padPlus() {
    this.setData({
      padNum: this.data.padNum >= 99 ? 99 : ++this.data.padNum
    })
  },
  showDatePopup() {
    if (!this.data.userInfo.exparea) {
      wx.showToast({
        title: '请选择取件地址',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    APIZPZ.getPickUpTime(this.data.userInfo.exparea, this.data.userInfo.expdtl).then((res: any) => {
      res.data = res.data.map((item: any) => {
        if (new Date().toISOString().match(/\d{4}-\d{2}-\d{2}/)?.[0] === item.day) {
          item.isToday = true;
        } else {
          item.isToday = false;
        }
        item.week = dayByChiness[item.dayOfWeek - 1];
        item.pickTime = item.time.filter((t: any) => t.status === 1);
        const currentDate = new Date(item.day);
        console.log(currentDate)
        item.day = currentDate.getMonth() + 1 + '月' + currentDate.getDate() + '日';
        item.dayFull = currentDate.toISOString().match(/\d{4}-\d{2}-\d{2}/)?.[0];
        return item;
      });
      this.setData({
        datePopupVisible: true,
        date: res.data.filter((item: any) => item.pickTime.length)
      });
    }).catch(() => {
      wx.showToast({
        title: '获取揽件时间失败',
        icon: 'none',
        duration: 2000
      });
    })
  },
  hideDatePopup() {
    this.setData({
      datePopupVisible: false
    });
    const indexs = this.data.selectedIndex.split('-');
    this.setData({
      pickUpTime: this.data.date[indexs[0]].day + "(" + this.data.date[indexs[0]].week + ')' + this.data.date[indexs[0]].pickTime[indexs[1]].label
    })
  },
  selectDay(e: any) {
    const data = e.currentTarget.dataset;
    this.setData({
      dayIndex: data.index
    });
  },
  selectTime(e: any) {
    const data = e.currentTarget.dataset;
    this.setData({
      timeIndex: data.index,
    });
    this.setData({
      selectedIndex: `${this.data.dayIndex}-${this.data.timeIndex}`
    });
  },
  dateCancel() {
    this.setData({
      datePopupVisible: false,
    })
  },
  agreementChange() {
    this.setData({
      agreement: !this.data.agreement
    })
  },
  chooseAddress() {
    wx.navigateTo({ url: `/pages/address/address-list/address-list?selectedId=${this.data.userInfo.id}&selected=true` })
  },
  showPriceTip() {
    this.setData({
      priceTipVisible: true,
    })
  },
  showExpressTip() {
    this.setData({
      expressTipVisible: true
    })
  },
  closeTip() {
    this.setData({
      priceTipVisible: false,
      expressTipVisible: false
    })
  },
  placeOrder() {
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    if (!(0 <= this.data.phoneNum && this.data.phoneNum <= 99)) {
      wx.showToast({
        title: '请输入正确的手机数量',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!(0 <= this.data.padNum && this.data.padNum <= 99)) {
      wx.showToast({
        title: '请输入正确的平板数量',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.padNum === 0 && this.data.phoneNum === 0) {
      wx.showToast({
        title: '请检查手机或平板数量',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!this.data.userInfo.exparea) {
      wx.showToast({
        title: '请选择取件地址',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!this.data.pickUpTime) {
      wx.showToast({
        title: '请选择取件时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!this.data.agreement) {
      wx.showToast({
        title: '请阅读并同意回收协议',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    APIZPZ.placeOrder({
      evalId: '',
      logistics: {
        apptime: this.data.pickUpTime,
        exparea: this.data.userInfo.exparea,
        expdtl: this.data.userInfo.expdtl,
        lnker: this.data.userInfo.lnker,
        lnktel: this.data.userInfo.lnktel,
      },
      modelId: '',
      orderWay: 2,
      padNum: this.data.padNum,
      phoneNum: this.data.phoneNum,
    }).then((res: any) => {
      wx.reLaunch({ url: `/pages/order/order-successful/order-successful?id=${res.data}` })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const id = wx.getStorageSync('addressId');
    console.log(id)
    if (id) {
      APIZPZ.getAddressDetail(id).then((res: any) => {
        if (!res.data) {
          this.setData({
            userInfo: {},
            date: [],
            pickUpTime: '',
          })
        }
        res.data.addressPreview = res.data.exparea.split('@').join(' ') + ' ' + res.data.expdtl;
        console.log(res.data)
        this.setData({
          userInfo: res.data,
          date: [],
          pickUpTime: '',
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})